package cn.edu.qfnu.oj.dao.impl;

import cn.edu.qfnu.common.dao.BaseDaoHib;
import cn.edu.qfnu.common.exception.db.NoRecordFoundException;
import cn.edu.qfnu.common.exception.db.WrongParameterException;
import cn.edu.qfnu.oj.dao.StudentDao;
import cn.edu.qfnu.oj.entity.Student;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

@Repository("studentDao")
public class StudentDaoImpl extends BaseDaoHib<Student, String> implements StudentDao {

    @Override
    public Student loginCheck(String username)
            throws NoRecordFoundException{

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
        detachedCriteria
                .add(Restrictions.or(Restrictions.eq("studentId", username))
                .add(Restrictions.or(Restrictions.eq("email", username))));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Student student = (Student) criteria.uniqueResult();

        if (student != null) {
            return student;
        } else {
            throw new NoRecordFoundException("用户不存在");
        }

    }

    @Override
    public boolean isExist(String studentId, String email){
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
        detachedCriteria
                .add(Restrictions.eq("studentId", studentId))
                .add(Restrictions.eq("email", email));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Student student = (Student) criteria.uniqueResult();

        return student != null;
    }

    @Override
    public boolean isRepeat(Student student) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
        detachedCriteria
                .add(Restrictions.or(Restrictions.eq("studentId", student.getStudentId()))
                .add(Restrictions.or(Restrictions.eq("email", student.getEmail()))));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Student reason = (Student) criteria.uniqueResult();

        return reason != null;
    }

    @Override
    public Student checkPassword(String studentId, String password) throws NoRecordFoundException {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);

        detachedCriteria
                .add(Restrictions.eq("studentId", studentId))
                .add(Restrictions.eq("password", password));

        Criteria criteria = detachedCriteria.getExecutableCriteria(currentSession());

        Student reason = (Student) criteria.uniqueResult();

        if (reason != null) {
            return reason;
        } else {
            throw new WrongParameterException("密码错误");
        }
    }

}
